import React from 'react'
import {observer} from 'mobx-react'
import {Modal} from 'antd'
import {QRCodeSVG} from 'qrcode.react'
import store from './store'

@observer
class QrcodeForm extends React.Component {
  state = {
    loading: false
  }

  // 生成唯一的注册码
  generateRegisterCode = () => {
    const timestamp = new Date().getTime()
    const random = Math.random().toString(36).substring(2, 8)
    return `GKRY-${timestamp}${random}`.toUpperCase()
  }

  // 获取二维码URL
  getQrcodeUrl = () => {
    const selectedCourses = store.selectedRows
    const courseIds = selectedCourses.map(x => x.id).join(',')

    const baseUrl = window.location.origin
    return `${baseUrl}/api/app/wx/oauth/?ids=${courseIds}`
  }

  // 下载二维码
  handleDownload = () => {
    const canvas = document.getElementById('qrcode-canvas')
    if (canvas) {
      const url = canvas.toDataURL('image/png')
      const a = document.createElement('a')
      a.download = '报名二维码.png'
      a.href = url
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
  }

  render() {
    const {selectedRows} = store
    if (!selectedRows.length) return null

    const qrcodeUrl = this.getQrcodeUrl()
    const schoolName = selectedRows[0].category_info.school

    return (
      <Modal
        visible
        width={500}
        maskClosable={false}
        title="报名二维码"
        onCancel={() => store.qrcodeVisible = false}
        footer={null}>
        <div style={{textAlign: 'center'}}>
          {/* 显示学校信息 */}
          <div style={{marginBottom: 16}}>
            <h4>就读学校: {schoolName}</h4>
            <p>应届高考年份: {selectedRows[0].year}</p>
          </div>

          {/* 显示选中的课程信息 */}
          <div style={{marginBottom: 16}}>
            <h4>已选择的课程:</h4>
            {selectedRows.map(course => (
              <div key={course.id} style={{margin: '8px 0'}}>
                <div>{course.name}</div>
                <div style={{fontSize: '12px', color: '#666'}}>
                  学习时间: {course.start_date} ~ {course.end_date}
                </div>
                <div style={{fontSize: '12px', color: '#666'}}>
                  课程价格: ¥{course.price}
                </div>
              </div>
            ))}
          </div>

          {/* 生成二维码 */}
          <QRCodeSVG
            id="qrcode-canvas"
            value={qrcodeUrl}
            size={200}
            level="M"  // 降低纠错级别以容纳更多数据
            includeMargin={true}
          />

          <div style={{marginTop: 16}}>
            <a onClick={this.handleDownload}>下载二维码</a>
          </div>

          {/* 提示信息 */}
          <div style={{marginTop: 16, fontSize: '12px', color: '#666'}}>
            扫描二维码完成报名信息填写
          </div>
        </div>
      </Modal>
    )
  }
}

export default QrcodeForm 